<template>
  <div class="topic-mindmap">
    <!-- 工具栏 -->
    <div class="mindmap-toolbar">
      <div class="toolbar-left">
        <!-- 根节点选择器 -->
        <el-select
          v-model="selectedRootId"
          placeholder="选择根节点查看详细结构"
          size="mini"
          style="width: 220px; margin-right: 10px;"
          clearable
          @change="handleRootNodeChange"
        >
          <el-option
            v-for="root in rootNodes"
            :key="root.id"
            :label="root.label"
            :value="root.id"
          >
            <span style="float: left">{{ root.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 12px">{{ root.childCount }}个子项</span>
          </el-option>
        </el-select>

        <el-button
          size="mini"
          icon="el-icon-refresh"
          :loading="loading"
          @click="refreshMindmap"
        >
          刷新
        </el-button>
      </div>

      <div class="toolbar-right">
        <!-- 快捷操作 -->
        <el-button-group size="mini">
          <el-button icon="el-icon-plus" title="添加子节点" @click="addChildFromMindmap" />
          <el-button icon="el-icon-edit" title="编辑节点" @click="editSelectedNode" />
          <el-button icon="el-icon-delete" title="删除节点" @click="deleteSelectedNode" />
        </el-button-group>

        <!-- 视图控制 -->
        <el-button-group size="mini" style="margin-left: 10px;">
          <el-button icon="el-icon-zoom-in" title="放大" @click="zoomIn" />
          <el-button icon="el-icon-zoom-out" title="缩小" @click="zoomOut" />
          <el-button icon="el-icon-refresh-left" title="重置视图" @click="resetView" />
        </el-button-group>

        <!-- 导出功能 -->
        <el-dropdown style="margin-left: 10px;" @command="handleExport">
          <el-button size="mini" type="primary">
            导出<i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="png">导出PNG图片</el-dropdown-item>
            <el-dropdown-item command="svg">导出SVG图片</el-dropdown-item>
            <el-dropdown-item command="json">导出JSON数据</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <!-- 帮助按钮 -->
        <el-button
          type="info"
          size="mini"
          icon="el-icon-question"
          circle
          title="操作帮助"
          @click="showHelp"
        />
      </div>
    </div>

    <!-- 思维导图容器 -->
    <div
      ref="mindmapContainer"
      v-loading="loading"
      class="mindmap-container"
      element-loading-text="加载思维导图..."
    >
      <!-- 空状态提示 -->
      <div v-if="!hasData && !loading" class="empty-state">
        <div class="empty-content">
          <svg-icon icon-class="tree" style="font-size: 48px; color: #C0C4CC; margin-bottom: 16px;" />
          <div v-if="rootNodes.length === 0">
            <h3 style="color: #606266; margin-bottom: 8px;">暂无话题数据</h3>
            <p style="color: #909399; margin-bottom: 16px;">点击下方按钮创建第一个话题节点</p>
            <el-button type="primary" @click="createRootNode">创建根话题</el-button>
          </div>
          <div v-else>
            <h3 style="color: #606266; margin-bottom: 8px;">请选择根节点查看详细结构</h3>
            <p style="color: #909399; margin-bottom: 16px;">
              当前有 {{ rootNodes.length }} 个根节点，选择一个查看其完整的思维导图结构
            </p>
            <div style="text-align: center;">
              <el-tag
                v-for="root in rootNodes.slice(0, 3)"
                :key="root.id"
                style="margin: 4px; cursor: pointer;"
                @click="handleRootNodeChange(root.id)"
              >
                {{ root.label }}
              </el-tag>
              <span v-if="rootNodes.length > 3" style="color: #909399;">...</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 节点编辑对话框 -->
    <el-dialog
      :title="nodeDialog.mode === 'create' ? '创建话题节点' : '编辑话题节点'"
      :visible.sync="nodeDialog.visible"
      width="50%"
      @close="closeNodeDialog"
    >
      <el-form ref="nodeForm" :model="nodeDialog.form" :rules="nodeDialog.rules" label-width="100px">
        <el-form-item label="关键词" prop="keyword">
          <el-input
            v-model="nodeDialog.form.keyword"
            placeholder="请输入关键词（必填）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input
            v-model="nodeDialog.form.title"
            placeholder="请输入标题（可选，默认使用关键词）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="nodeDialog.form.description"
            type="textarea"
            placeholder="请输入描述（可选）"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="搜索量">
              <el-input-number
                v-model="nodeDialog.form.volume"
                :min="0"
                :max="10000000"
                placeholder="关键词搜索量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度">
              <el-input-number
                v-model="nodeDialog.form.difficulty"
                :min="1"
                :max="100"
                placeholder="SEO难度(1-100)"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="AI段落数">
              <el-input-number
                v-model="nodeDialog.form.ai_paragraph"
                :min="1"
                :max="20"
                placeholder="AI生成段落数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重要星级">
              <el-rate
                v-model="nodeDialog.form.star"
                :max="5"
                show-text
                :texts="['很低', '较低', '一般', '重要', '很重要']"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="nodeDialog.mode === 'edit'" label="审核状态">
          <el-select v-model="nodeDialog.form.status" placeholder="选择状态" style="width: 200px">
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeNodeDialog">取消</el-button>
        <el-button
          type="primary"
          :loading="nodeDialog.saving"
          @click="saveNode"
        >
          {{ nodeDialog.mode === 'create' ? '创建' : '保存' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 帮助对话框 -->
    <el-dialog
      title="操作帮助"
      :visible.sync="helpDialog.visible"
      width="60%"
    >
      <div class="help-content">
        <el-card shadow="never" class="help-section">
          <div slot="header" class="help-section-title">
            <svg-icon icon-class="guide" style="margin-right: 8px;" />
            基本操作
          </div>
          <ul class="help-list">
            <li><strong>双击节点</strong>：编辑节点内容</li>
            <li><strong>右键节点</strong>：显示上下文菜单（添加子节点、删除节点等）</li>
            <li><strong>拖拽节点</strong>：移动节点位置（支持重新设置父子关系）</li>
            <li><strong>鼠标滚轮</strong>：缩放思维导图</li>
            <li><strong>拖拽空白区域</strong>：移动整个导图视图</li>
          </ul>
        </el-card>

        <el-card shadow="never" class="help-section">
          <div slot="header" class="help-section-title">
            <svg-icon icon-class="tree" style="margin-right: 8px;" />
            话题管理
          </div>
          <ul class="help-list">
            <li>每个节点代表一个话题，显示关键词作为节点标题</li>
            <li>节点颜色表示不同状态：蓝色(进行中)、绿色(已完成)、灰色(待开始)</li>
            <li>可以通过拖拽重新组织话题的层级关系</li>
            <li>删除节点前需要先删除其所有子节点</li>
          </ul>
        </el-card>

        <el-card shadow="never" class="help-section">
          <div slot="header" class="help-section-title">
            <svg-icon icon-class="download" style="margin-right: 8px;" />
            导出功能
          </div>
          <ul class="help-list">
            <li><strong>PNG图片</strong>：导出为图片文件，适合分享和展示</li>
            <li><strong>SVG图片</strong>：导出为矢量图，适合编辑和缩放</li>
            <li><strong>JSON数据</strong>：导出数据结构，可用于备份或其他用途</li>
          </ul>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="helpDialog.visible = false">我知道了</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTopicMindmapData, createTopicNode, updateTopicNode, deleteTopicNode, getRootTopicNodes, getTopicSubtree } from '@/api/cms/topic_mindmap'
import { Get as getWebs } from '@/api/cms/web'

export default {
  name: 'TopicMindmap',
  props: {
    selectedWebId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      loading: false,
      hasData: false,
      mindmapInstance: null,
      currentData: null,

      // Web网站管理
      webList: [],

      // 根节点管理
      rootNodes: [], // 根节点列表
      selectedRootId: null, // 当前选中的根节点ID
      viewMode: 'overview', // overview: 概览模式, detail: 详细模式

      // 节点编辑对话框
      nodeDialog: {
        visible: false,
        mode: 'create', // create | edit
        saving: false,
        currentNode: null,
        form: {
          keyword: '',
          title: '',
          description: '',
          volume: 0,
          difficulty: 30,
          ai_paragraph: 1,
          star: 1,
          status: 'draft',
          parent_id: null
        },
        rules: {
          keyword: [
            { required: true, message: '请输入关键词', trigger: 'blur' },
            { min: 1, max: 100, message: '关键词长度应在1-100字符之间', trigger: 'blur' }
          ]
        }
      },

      // 帮助对话框
      helpDialog: {
        visible: false
      }
    }
  },

  mounted() {
    this.initMindmap()
    this.loadWebList()
    if (this.selectedWebId) {
      this.loadRootNodes()
    }
  },

  watch: {
    selectedWebId: {
      handler(newWebId, oldWebId) {
        if (newWebId !== oldWebId) {
          this.selectedRootId = null
          this.rootNodes = []
          this.currentData = null
          this.hasData = false

          if (newWebId) {
            this.loadRootNodes()
          }
        }
      },
      immediate: false
    }
  },

  beforeDestroy() {
    if (this.mindmapInstance) {
      this.mindmapInstance.destroy()
    }
  },

  methods: {
    // 初始化思维导图
    initMindmap() {
      const container = this.$refs.mindmapContainer
      if (!container) return

      // 检查 jsMind 是否已加载
      if (typeof window.jsMind === 'undefined') {
        console.warn('jsMind library not loaded yet, retrying...')
        // 延迟重试
        setTimeout(() => {
          this.initMindmap()
        }, 500)
        return
      }

      // jsMind 配置选项
      const options = {
        container: container,
        theme: 'primary',
        editable: true,
        support_html: true,
        view: {
          hmargin: 100,
          vmargin: 50,
          line_width: 2,
          line_color: '#558B2F'
        },
        layout: {
          hspace: 30,
          vspace: 20,
          pspace: 13
        },
        shortcut: {
          enable: true,
          handles: {},
          mapping: {
            addchild: [45, 4096 + 13], // Insert, Ctrl+Enter
            addbrother: 13, // Enter
            editnode: 113, // F2
            delnode: 46, // Delete
            toggle: 32, // Space
            left: 37, // Left
            up: 38, // Up
            right: 39, // Right
            down: 40 // Down
          }
        }
      }

      try {
        // 初始化 jsMind 实例
        // eslint-disable-next-line new-cap
        this.mindmapInstance = new window.jsMind(options)

        // 绑定事件
        this.bindMindmapEvents()

        console.log('jsMind initialized successfully')
      } catch (error) {
        console.error('Failed to initialize jsMind:', error)
        this.$message.error('思维导图初始化失败')
      }
    },

    // 绑定思维导图事件
    bindMindmapEvents() {
      if (!this.mindmapInstance) return

      // 监听节点选择事件
      this.mindmapInstance.add_event_listener((type, data) => {
        console.log('jsMind 事件:', type, data)

        switch (type) {
          case 'select_node':
            this.handleNodeSelect(data)
            break
          case 'edit_node':
            this.handleNodeEdit(data)
            break
          case 'resize':
            this.handleResize(data)
            break
        }
      })
    },

    // 处理节点选择
    handleNodeSelect(node) {
      console.log('选择节点:', node)
    },

    // 处理节点编辑
    handleNodeEdit(node) {
      console.log('编辑节点:', node)
      this.editNode(node.id)
    },

    // 处理窗口调整
    handleResize() {
      this.$nextTick(() => {
        if (this.mindmapInstance) {
          this.mindmapInstance.resize()
        }
      })
    },

    // 显示思维导图
    showMindmap(data) {
      if (!this.mindmapInstance || !data) return

      // 转换数据格式为 jsMind 需要的格式
      const mindData = this.convertToJsMindFormat(data)

      // 显示思维导图
      this.mindmapInstance.show(mindData)
    },

    // 转换数据格式
    convertToJsMindFormat(data) {
      const MAX_CHILDREN_AFTER_LEVEL2 = 10

      const convertNode = (node, level = 0) => {
        const mindNode = {
          id: node.id.toString(),
          topic: node.topic || '未命名',
          data: {
            title: node.title,
            description: node.description,
            progress: node.progress || 0,
            status: node.status,
            volume: node.volume,
            difficulty: node.difficulty,
            star: node.star,
            is_finished: node.is_finished
          }
        }

        // 添加样式
        if (node.id === 'overview_root') {
          // 概览模式的虚拟根节点
          mindNode.background_color = '#409EFF'
          mindNode.foreground_color = '#fff'
        } else if (node.is_finished) {
          mindNode.background_color = '#67c23a'
          mindNode.foreground_color = '#fff'
        } else if (node.progress > 0) {
          mindNode.background_color = '#1EB7E6'
          mindNode.foreground_color = '#fff'
        } else {
          mindNode.background_color = '#909399'
          mindNode.foreground_color = '#fff'
        }

        // 转换子节点，在二级目录之后限制显示数量
        if (node.children && node.children.length > 0) {
          let childrenToShow = node.children
          let hasMoreChildren = false

          // 如果是二级目录之后（level >= 2）且子节点超过10个，只显示前10个
          if (level >= 2 && node.children.length > MAX_CHILDREN_AFTER_LEVEL2) {
            childrenToShow = node.children.slice(0, MAX_CHILDREN_AFTER_LEVEL2)
            hasMoreChildren = true
          }

          mindNode.children = childrenToShow.map(child => convertNode(child, level + 1))

          // 如果有更多子节点，添加一个提示节点
          if (hasMoreChildren) {
            const moreNode = {
              id: `more_${node.id}_${Date.now()}`,
              topic: `...还有${node.children.length - MAX_CHILDREN_AFTER_LEVEL2}个子项`,
              background_color: '#E6A23C',
              foreground_color: '#fff',
              data: {
                isMoreNode: true,
                parentId: node.id,
                totalCount: node.children.length,
                showingCount: MAX_CHILDREN_AFTER_LEVEL2
              }
            }
            mindNode.children.push(moreNode)
          }
        }

        return mindNode
      }

      return {
        meta: {
          name: '话题框架图',
          author: 'kikimami',
          version: '1.0'
        },
        format: 'node_tree',
        data: convertNode(data, 0)
      }
    },

    // 获取节点颜色
    getNodeColor(node) {
      if (node.is_finished) return '#67c23a' // 绿色：已完成
      if (node.progress > 0) return '#1EB7E6' // 蓝色：进行中
      return '#909399' // 灰色：未开始
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'draft': '草稿',
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已驳回'
      }
      return statusMap[status] || status
    },

    // 加载根节点列表
    async loadRootNodes() {
      if (!this.selectedWebId) {
        this.rootNodes = []
        this.hasData = false
        return
      }

      this.loading = true

      try {
        const response = await getRootTopicNodes(this.selectedWebId)

        if (response.success && response.data) {
          // 使用优化的API，直接获取根节点数据
          const rootData = response.data || []

          this.rootNodes = rootData.map(root => ({
            id: root.id,
            label: root.title || root.keyword,
            childCount: root.children_count || 0,
            data: root
          }))

          console.log('加载的根节点:', this.rootNodes)

          // 如果有根节点，显示概览模式（所有根节点的2级结构）
          if (this.rootNodes.length > 0) {
            this.viewMode = 'overview'
            this.loadOverviewData()
          } else {
            this.hasData = false
          }
        } else {
          this.$message.error(response.msg || '加载根节点失败')
          this.hasData = false
        }
      } catch (error) {
        console.error('加载根节点错误:', error)
        this.$message.error('加载失败：' + (error.message || '网络错误'))
        this.hasData = false
      } finally {
        this.loading = false
      }
    },

    // 加载概览数据（所有根节点的2级结构）
    async loadOverviewData() {
      if (!this.rootNodes.length) return

      try {
        // 为概览模式加载前几个根节点的基本子树数据
        const overviewPromises = this.rootNodes.slice(0, 5).map(async(root) => {
          try {
            const response = await getTopicSubtree(root.id)
            if (response.success && response.data) {
              // 只保留2级结构，限制显示的子节点数量
              const limitedData = {
                ...response.data,
                topic: response.data.topic || response.data.keyword || root.label,
                children: (response.data.children || []).slice(0, 3).map(child => ({
                  ...child,
                  children: [] // 概览模式不显示第三级
                }))
              }
              return limitedData
            }
            return {
              id: root.id,
              topic: root.label,
              title: root.label,
              children: []
            }
          } catch (error) {
            console.error(`加载根节点 ${root.id} 数据失败:`, error)
            return {
              id: root.id,
              topic: root.label,
              title: root.label,
              children: []
            }
          }
        })

        const rootDataList = await Promise.all(overviewPromises)

        // 构造概览数据：创建一个虚拟根节点，包含加载的根节点数据
        const overviewData = {
          id: 'overview_root',
          topic: '话题框架概览',
          title: '话题框架概览',
          keyword: '话题框架概览',
          children: rootDataList
        }

        console.log('概览数据构建完成:', overviewData)

        this.currentData = overviewData
        this.hasData = true

        if (this.mindmapInstance) {
          this.showMindmap(this.currentData)
        }
      } catch (error) {
        console.error('加载概览数据错误:', error)
        this.$message.error('加载概览失败：' + (error.message || '网络错误'))
      }
    },

    // 处理根节点选择变化
    async handleRootNodeChange(rootId) {
      if (!rootId) {
        // 清空选择，回到概览模式
        this.selectedRootId = null
        this.viewMode = 'overview'
        this.loadOverviewData()
        return
      }

      this.loading = true
      this.viewMode = 'detail'

      try {
        const response = await getTopicSubtree(rootId)

        console.log('子树API响应:', response)

        if (response.success && response.data) {
          // 优化的API直接返回完整的子树数据
          const treeData = response.data

          if (treeData && typeof treeData === 'object') {
            // 确保数据格式正确，添加必要的字段
            this.currentData = {
              ...treeData,
              topic: treeData.topic || treeData.keyword || treeData.title || '未命名话题'
            }
            this.hasData = true

            console.log('处理后的子树数据:', this.currentData)

            if (this.mindmapInstance) {
              this.showMindmap(this.currentData)
            }
          } else {
            this.currentData = null
            this.hasData = false
            this.$message.warning('该节点暂无数据')
          }
        } else {
          this.$message.error(response.msg || '加载子树失败')
          this.hasData = false
        }
      } catch (error) {
        console.error('加载子树错误:', error)
        this.$message.error('加载失败：' + (error.message || '网络错误'))
        this.hasData = false
      } finally {
        this.loading = false
      }
    },

    // 加载思维导图数据
    async loadMindmapData() {
      this.loading = true

      try {
        const response = await getTopicMindmapData()

        if (response.success) {
          this.currentData = response.data
          this.hasData = !!response.data && (response.data.children?.length > 0 || response.data.id > 0)

          if (this.hasData && this.mindmapInstance) {
            this.showMindmap(this.currentData)
          }
        } else {
          this.$message.error(response.msg || '加载失败')
        }
      } catch (error) {
        console.error('加载思维导图数据错误:', error)
        this.$message.error('加载失败')
      } finally {
        this.loading = false
      }
    },

    // 刷新思维导图
    refreshMindmap() {
      if (this.viewMode === 'detail' && this.selectedRootId) {
        // 详细模式，重新加载选中的根节点
        this.handleRootNodeChange(this.selectedRootId)
      } else {
        // 概览模式，重新加载根节点列表
        this.loadRootNodes()
      }
    },

    // 缩放控制
    zoomIn() {
      if (this.mindmapInstance) {
        this.mindmapInstance.view.zoom_in()
      }
    },

    zoomOut() {
      if (this.mindmapInstance) {
        this.mindmapInstance.view.zoom_out()
      }
    },

    resetView() {
      if (this.mindmapInstance) {
        this.mindmapInstance.view.zoom_reset()
        this.mindmapInstance.view.center_root()
      }
    },

    // 导出功能
    handleExport(command) {
      switch (command) {
        case 'png':
          this.exportAsPNG()
          break
        case 'svg':
          this.exportAsSVG()
          break
        case 'json':
          this.exportAsJSON()
          break
      }
    },

    exportAsPNG() {
      if (this.mindmapInstance) {
        const canvas = this.mindmapInstance.screenshot.shoot()
        const link = document.createElement('a')
        link.download = 'topic-mindmap.png'
        link.href = canvas.toDataURL()
        link.click()
        this.$message.success('PNG图片导出成功')
      } else {
        this.$message.error('思维导图未初始化')
      }
    },

    exportAsSVG() {
      this.$message.info('SVG导出功能将在后续版本支持')
    },

    exportAsJSON() {
      if (this.currentData) {
        const dataStr = JSON.stringify(this.currentData, null, 2)
        const blob = new Blob([dataStr], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = 'topic-mindmap.json'
        link.click()
        URL.revokeObjectURL(url)
        this.$message.success('JSON数据导出成功')
      }
    },

    // 创建根节点
    createRootNode() {
      if (!this.selectedWebId) {
        this.$message.warning('请先选择一个网站')
        return
      }

      this.nodeDialog.mode = 'create'
      this.nodeDialog.currentNode = null
      this.resetNodeForm()
      this.nodeDialog.form.parent_id = null
      this.nodeDialog.form.web_id = this.selectedWebId
      this.nodeDialog.visible = true
    },

    // 添加子节点
    addChildNode(parentId) {
      if (!this.selectedWebId) {
        this.$message.warning('请先选择一个网站')
        return
      }

      this.nodeDialog.mode = 'create'
      this.nodeDialog.currentNode = null
      this.resetNodeForm()
      this.nodeDialog.form.parent_id = parentId || null
      this.nodeDialog.form.web_id = this.selectedWebId
      this.nodeDialog.visible = true
    },

    // 右键菜单添加子节点
    addChildFromMindmap() {
      const selectedNode = this.mindmapInstance ? this.mindmapInstance.get_selected_node() : null
      if (selectedNode) {
        this.addChildNode(parseInt(selectedNode.id))
      } else {
        this.addChildNode(null) // 创建根节点
      }
    },

    // 编辑选中的节点
    editSelectedNode() {
      const selectedNode = this.mindmapInstance ? this.mindmapInstance.get_selected_node() : null
      if (selectedNode) {
        this.editNode(parseInt(selectedNode.id))
      } else {
        this.$message.warning('请先选择一个节点')
      }
    },

    // 删除选中的节点
    deleteSelectedNode() {
      const selectedNode = this.mindmapInstance ? this.mindmapInstance.get_selected_node() : null
      if (selectedNode) {
        this.confirmDeleteNode(parseInt(selectedNode.id))
      } else {
        this.$message.warning('请先选择一个节点')
      }
    },

    // 编辑节点
    editNode(nodeId) {
      const node = this.findNodeById(this.currentData, nodeId)
      if (!node) {
        this.$message.error('未找到节点')
        return
      }

      this.nodeDialog.mode = 'edit'
      this.nodeDialog.currentNode = node
      this.nodeDialog.form = {
        id: node.id,
        keyword: node.topic,
        title: node.title || '',
        description: node.description || '',
        volume: node.volume || 0,
        difficulty: node.difficulty || 30,
        ai_paragraph: node.ai_paragraph || 1,
        star: node.star || 1,
        status: node.status || 'draft',
        parent_id: node.parent_id,
        web_id: node.web_id || null
      }
      this.nodeDialog.visible = true
    },

    // 删除节点确认
    confirmDeleteNode(nodeId) {
      const node = this.findNodeById(this.currentData, nodeId)
      if (!node) {
        this.$message.error('未找到节点')
        return
      }

      // 检查是否有子节点
      if (node.children && node.children.length > 0) {
        this.$message.warning('请先删除子节点')
        return
      }

      this.$confirm(
        `确定要删除话题节点"${node.topic}"吗？`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.deleteNode(nodeId)
      })
    },

    // 删除节点
    async deleteNode(nodeId) {
      try {
        const response = await deleteTopicNode(nodeId)

        if (response.success) {
          this.$message.success('节点删除成功')

          // 刷新当前视图
          if (this.viewMode === 'detail' && this.selectedRootId) {
            // 如果删除的是当前选中的根节点，返回概览模式
            if (nodeId === this.selectedRootId) {
              this.selectedRootId = null
              this.viewMode = 'overview'
              this.loadRootNodes()
            } else {
              // 否则重新加载当前选中的根节点数据
              this.handleRootNodeChange(this.selectedRootId)
            }
          } else {
            // 如果在概览模式，重新加载根节点列表
            this.loadRootNodes()
          }
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除节点错误:', error)
        this.$message.error('删除失败：' + (error.message || '网络错误'))
      }
    },

    // 保存节点
    async saveNode() {
      this.$refs.nodeForm.validate(async(valid) => {
        if (!valid) return

        this.nodeDialog.saving = true

        try {
          let response
          if (this.nodeDialog.mode === 'create') {
            response = await createTopicNode(this.nodeDialog.form)
          } else {
            response = await updateTopicNode(this.nodeDialog.form)
          }

          if (response.success) {
            this.$message.success(this.nodeDialog.mode === 'create' ? '节点创建成功' : '节点更新成功')
            this.closeNodeDialog()

            // 刷新当前视图
            if (this.viewMode === 'detail' && this.selectedRootId) {
              // 如果在详细模式，重新加载当前选中的根节点数据
              this.handleRootNodeChange(this.selectedRootId)
            } else {
              // 如果在概览模式，重新加载根节点列表
              this.loadRootNodes()
            }
          } else {
            this.$message.error(response.msg || '保存失败')
          }
        } catch (error) {
          console.error('保存节点错误:', error)
          this.$message.error('保存失败：' + (error.message || '网络错误'))
        } finally {
          this.nodeDialog.saving = false
        }
      })
    },

    // 关闭节点对话框
    closeNodeDialog() {
      this.nodeDialog.visible = false
      this.nodeDialog.saving = false
      this.nodeDialog.currentNode = null
      this.resetNodeForm()
    },

    // 重置节点表单
    resetNodeForm() {
      this.nodeDialog.form = {
        keyword: '',
        title: '',
        description: '',
        volume: 0,
        difficulty: 30,
        ai_paragraph: 1,
        star: 1,
        status: 'draft',
        parent_id: null,
        web_id: this.selectedWebId || null
      }

      this.$nextTick(() => {
        if (this.$refs.nodeForm) {
          this.$refs.nodeForm.clearValidate()
        }
      })
    },

    // 查找节点
    findNodeById(node, id) {
      if (!node) return null
      if (node.id === id) return node

      if (node.children) {
        for (const child of node.children) {
          const found = this.findNodeById(child, id)
          if (found) return found
        }
      }

      return null
    },

    // 显示帮助
    showHelp() {
      this.helpDialog.visible = true
    },

    // 加载Web网站列表
    async loadWebList() {
      try {
        const response = await getWebs(null, 'page=1&pagesize=100')
        if (response.data && response.data.data) {
          this.webList = response.data.data
          console.log('加载的Web列表:', this.webList)
        }
      } catch (error) {
        console.error('加载Web列表失败:', error)
        // 不影响主功能，静默处理
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.topic-mindmap {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;

  .mindmap-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: white;
    border-bottom: 1px solid #e4e7ed;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .toolbar-left {
      display: flex;
      align-items: center;
      gap: 15px;

      .mindmap-title {
        margin: 0;
        color: #303133;
        font-size: 18px;
        display: flex;
        align-items: center;
      }
    }

    .toolbar-right {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .mindmap-container {
    flex: 1;
    position: relative;
    background: white;
    overflow: hidden;

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      .empty-content {
        text-align: center;
        color: #909399;
      }
    }
  }
}

// jsMind 思维导图自定义样式
::v-deep .jsmind-inner {
  font-family: 'Microsoft YaHei', Arial, sans-serif;

  jmnode {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
      transform: scale(1.05);
    }
  }

  jmexpander {
    border-radius: 50%;
    border: 2px solid #1EB7E6;
    background: #fff;
    color: #1EB7E6;
    font-weight: bold;

    &:hover {
      background: #1EB7E6;
      color: #fff;
    }
  }
}

// 帮助内容样式
.help-content {
  .help-section {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .help-section-title {
      display: flex;
      align-items: center;
      font-weight: bold;
      color: #303133;
    }

    .help-list {
      margin: 0;
      padding-left: 20px;

      li {
        margin-bottom: 8px;
        color: #606266;
        line-height: 1.5;

        strong {
          color: #303133;
        }
      }
    }
  }
}
</style>
